import { useEffect, useState } from 'react';

const Home = () => 'Home';
const Search = () => 'Search';
const Comment = () => 'Comment';

export const Router = () => {
  // 定义组件状态
  const [path, setPath] = useState(window.location.hash.slice(1));

  useEffect(() => {
    // 监听url hash 变化
    const handleHashChange = () => {
      setPath(window.location.hash.slice(1));
    };

    // 给 window 绑定 hashchange 事件，
    // 来监听浏览器地址栏中 # 后面内容的变化，也就是 hash 改变
    window.addEventListener('hashchange', handleHashChange);

    // 清理函数
    return () => {
      window.removeEventListener('hashchange', handleHashChange);
    };
  }, []);

  return (
    <div>
      <ul>
        <li>
          <a href="#/home">首页</a>
        </li>
        <li>
          <a href="#/comment">评论</a>
        </li>
        <li>
          <a href="#/search">搜索</a>
        </li>
      </ul>
      {/* 基于url地址栏的条件渲染 */}
      <div>
        {path === '/home' && <Home></Home>}
        {path === '/search' && <Search></Search>}
        {path === '/comment' && <Comment></Comment>}
      </div>
    </div>
  );
};
